package com.zsd.android.glidelib;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import com.zsd.android.glidelib.fragment.ActivityFragmentManager;
import com.zsd.android.glidelib.fragment.AppCompatFragmentManager;

public class RequestManger {

    private final String ACTIVITY_TAG_NAME = "activity_tab_name";
    private final String APP_COMPAT_ACtiVIty_TAG_NAME = "app_compat_activity_tab_name";
    private final int NEXT_MSG = 234;
    private Context mContext;
    private RequestTagEngine engine;
    private static Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });
    //构造代码块,不用在每个构造方里面去实例化了
    {
        if (engine == null) {
            engine = new RequestTagEngine();
        }
    }

    public RequestManger(Context mContext) {
        this.mContext = mContext;
    }

    public RequestManger(Activity activity) {
        this.mContext = activity;
        android.app.FragmentManager fManager = activity.getFragmentManager();
        android.app.Fragment fragment = fManager.findFragmentByTag(ACTIVITY_TAG_NAME);
        if (fragment == null) {
            fragment = new ActivityFragmentManager(engine);
            fManager.beginTransaction().add(fragment, ACTIVITY_TAG_NAME).commitAllowingStateLoss();
        }
        mHandler.sendEmptyMessage(NEXT_MSG);
    }

    public RequestManger(AppCompatActivity appCompatActivity) {
        this.mContext = appCompatActivity;
        FragmentManager fManager = appCompatActivity.getSupportFragmentManager();
        Fragment fragment = fManager.findFragmentByTag(APP_COMPAT_ACtiVIty_TAG_NAME);
        if (fragment == null) {
            fragment = new AppCompatFragmentManager(engine);
            fManager.beginTransaction().add(fragment, APP_COMPAT_ACtiVIty_TAG_NAME).commitAllowingStateLoss();
        }
        mHandler.sendEmptyMessage(NEXT_MSG);
    }

    public RequestTagEngine load(String url) {
        mHandler.removeMessages(NEXT_MSG);
        //把值传递给资源加载引擎
        engine.loadValueInitAction(mContext, url);
        return engine;
    }
}
